/**
 * Created with IntelliJ IEDA.
 * Description:
 * User:86186
 * Date:2023-04-19
 * Time:21:51
 */

import java.util.Arrays;
import java.util.Stack;

/**
 * BM11链表相加(二)
 * 利用栈的思想，先将两个链表的节点值逐一压入栈中，然后从栈中弹出元素进行相加，
 * 用 carry 变量记录进位信息，将每次相加的结果作为新节点插入到结果链表的头部。
 * 最后返回结果链表即可
 */

public class addInList {
    public static void main(String[] args) {
        // 构造链表 1 -> 2 -> 3
        ListNode head1 = new ListNode(1);
        head1.next = new ListNode(2);
        head1.next.next = new ListNode(3);

        // 构造链表 4 -> 5 -> 6 -> 7
        ListNode head2 = new ListNode(4);
        head2.next = new ListNode(5);
        head2.next.next = new ListNode(6);
        head2.next.next.next = new ListNode(7);

        // 预期结果为 5 -> 7 -> 9 -> 0
        ListNode result = addInList(head1, head2);

        // 检查结果是否正确
        boolean correct = result.val == 5 && result.next.val == 7 && result.next.next.val == 9 && result.next.next.next.val == 0;
        System.out.println(correct ? "测试通过" : "测试失败");
    }
    public static ListNode addInList(ListNode head1, ListNode head2) {
        Stack<Integer> stack1 = new Stack<>();
        Stack<Integer> stack2 = new Stack<>();
        while (head1 != null) {
            stack1.push(head1.val);
            head1 = head1.next;
        }
        while (head2 != null) {
            stack2.push(head2.val);
            head2 = head2.next;
        }
        ListNode dummy = new ListNode(0);
        int carry = 0;
        while (!stack1.isEmpty() || !stack2.isEmpty() || carry != 0) {
            int sum = carry;
            if (!stack1.isEmpty()) {
                sum += stack1.pop();
            }
            if (!stack2.isEmpty()) {
                sum += stack2.pop();
            }
            ListNode node = new ListNode(sum % 10);
            node.next = dummy.next;
            dummy.next = node;
            carry = sum / 10;
        }
        return dummy.next;
    }

}
